﻿﻿﻿using DeviceCommons.DeviceMessages.Models;
using DeviceCommons.DeviceMessages.Models.V1;
using DeviceCommons.Validation;

namespace DeviceCommons.DeviceMessages.Builders
{
    public class DeviceInfoBuilder
    {
        private readonly DeviceMessageInfo _device;
        private readonly List<DeviceMessageInfoReading> _readings = new();

        public DeviceInfoBuilder(DeviceMessageInfo device) => _device = device;

        public DeviceInfoBuilder AddReading(short timeOffset, Action<DeviceInfoReadingBuilder> config)
        {
            // 前置验证
            DeviceMessageValidator.ValidateTimeOffset(timeOffset);
            ArgumentNullException.ThrowIfNull(config, nameof(config));
            
            // 验证读数数量限制
            DeviceMessageValidator.ValidateReadingCount(_readings.Count + 1);

            var reading = new DeviceMessageInfoReading
            {
                TimeOffset = timeOffset
            };

            var builder = new DeviceInfoReadingBuilder(reading, _device.DeviceType);
            config(builder);
            _readings.Add(builder.Build());
            return this;
        }

        public DeviceMessageInfo Build()
        {
            _device.Reading = new DeviceMessageInfoReadings
            {
                ReadingArray = _readings.ToArray()
            };
            return _device;
        }
    }
}
